/**
 * zss-ol-map 示例项目
 * 演示各种图层和功能的使用
 */

import { Map, MapType, ClusterLayer, TrackLayer, HeatmapLayer, ImageLayer, VectorLayer, VectorTileLayer, LayerManager, StyleCache, DataAdapter, StyleUtil, Popup, Marker, Measure, MeasureType, FullScreen, Search, Route, SpatialAnalysis, LogisticsAnalyzer } from 'zss-ol-map';
import 'ol/ol.css';
import { ExtensionManager, MeasurementExtension, RouteExtension } from 'zss-ol-map';

// 全局变量
let map = null;
let clusterLayer = null;
let trackLayer = null;
let heatmapLayer = null;
let vectorLayer = null;
let vectorTileLayer = null;
let dataLayer = null;
let measureTool = null;
let markers = [];
let searchTool = null;
let routeTool = null;
let dataAdapter = null;
let styleCache = null;

// 初始化地图
function initMap() {
  map = new Map({
    target: 'map',
    center: [116.397428, 39.90923], // 北京
    zoom: 10,
    mapType: MapType.GAODE,
    zoomControl: true,
    scaleLine: true,
    mousePosition: true
  });

  map.on('ready', () => {
    console.log('地图初始化完成');
    updateInfo('地图初始化完成');
  });

  map.on('click', (event) => {
    const coordinate = event.coordinate;
    console.log('点击坐标:', coordinate);
    
    // 显示弹窗示例
    // const popup = new Popup({
    //   id: 'click-popup',
    //   showCloseButton: true
    // });
    // popup.setContent(`
    //   <div>
    //     <h4>点击位置</h4>
    //     <p>经度: ${coordinate[0].toFixed(6)}</p>
    //     <p>纬度: ${coordinate[1].toFixed(6)}</p>
    //   </div>
    // `);
    // const lonLat = map.getCenter();
    // popup.show(map.getOlMap(), lonLat);
    // map.addPopup(popup);
  });
}

// 切换地图类型
window.switchMapType = function(type) {
  if (!map) return;
  
  const mapTypeMap = {
    'gaode': MapType.GAODE,
    'baidu': MapType.BAIDU,
    'osm': MapType.OSM
  };
  
  map.setMapType(mapTypeMap[type]);
  updateInfo(`切换到${type}地图`);
};

// 聚合图层相关
window.addClusterLayer = function() {
  if (!map) return;
  
  if (clusterLayer) {
    map.removeLayer(clusterLayer);
  }
  
  clusterLayer = new ClusterLayer({
    id: 'cluster',
    distance: 40,
    showCount: true
  });
  
  map.addLayer(clusterLayer);
  
  // 添加示例数据
  const points = generateRandomPoints([116.397428, 39.90923], 20, 0.1);
  clusterLayer.addFeatures(points.map((coord, index) => ({
    id: `point_${index}`,
    geometry: coord,
    properties: {
      name: `点${index + 1}`,
      value: Math.floor(Math.random() * 100)
    }
  })));
  
  // 监听点击事件
  clusterLayer.on('clusterclick', (data) => {
    console.log('聚合点被点击:', data);
    updateInfo(`聚合点被点击，包含${data.count}个点`);
  });
  
  clusterLayer.on('pointclick', (data) => {
    console.log('点被点击:', data);
    updateInfo(`点被点击: ${data.feature.get('name') || '未命名'}`);
  });
  
  updateInfo('聚合图层已添加');
};

window.updateClusterData = function() {
  if (!clusterLayer) return;
  
  const points = generateRandomPoints([116.397428, 39.90923], 30, 0.15);
  clusterLayer.updateData(points.map((coord, index) => ({
    id: `point_${index}`,
    geometry: coord,
    properties: {
      name: `点${index + 1}`,
      value: Math.floor(Math.random() * 100)
    }
  })));
  
  updateInfo('聚合图层数据已更新');
};

window.removeClusterLayer = function() {
  if (!map || !clusterLayer) return;
  
  map.removeLayer(clusterLayer);
  clusterLayer = null;
  updateInfo('聚合图层已移除');
};

// 轨迹图层相关
window.addTrackLayer = function() {
  if (!map) return;
  
  if (trackLayer) {
    map.removeLayer(trackLayer);
  }
  
  trackLayer = new TrackLayer({
    id: 'track',
    showKeyPoints: true,
    animationSpeed: 100,
    autoPlay: false
  });
  
  map.addLayer(trackLayer);
  
  // 生成示例轨迹数据
  const trackPoints = generateTrackPoints([116.397428, 39.90923], 20);
  trackLayer.setTrackData(trackPoints);
  
  // 监听播放事件
  trackLayer.on('playstart', () => {
    updateInfo('轨迹播放开始');
  });
  
  trackLayer.on('playstop', () => {
    updateInfo('轨迹播放结束');
  });
  
  trackLayer.on('playprogress', (data) => {
    const progress = Math.floor(data.progress * 100);
    updateInfo(`轨迹播放进度: ${progress}%`);
  });
  
  // 缩放到轨迹范围
  if (trackPoints.length > 0) {
    const coords = trackPoints.map(p => p.coordinate);
    const extent = getExtentFromCoords(coords);
    map.fitExtent(extent, 1000);
  }
  
  updateInfo('轨迹图层已添加');
};

window.playTrack = function() {
  if (!trackLayer) return;
  trackLayer.play();
};

window.pauseTrack = function() {
  if (!trackLayer) return;
  trackLayer.pause();
};

window.stopTrack = function() {
  if (!trackLayer) return;
  trackLayer.stop();
};

// 热力图图层相关
window.addHeatmapLayer = function() {
  if (!map) return;
  
  if (heatmapLayer) {
    map.removeLayer(heatmapLayer);
  }
  
  heatmapLayer = new HeatmapLayer({
    id: 'heatmap',
    radius: 20,
    blur: 15,
    gradient: ['#00f', '#0ff', '#0f0', '#ff0', '#f00'],
    adaptiveRadius: true
  });
  
  map.addLayer(heatmapLayer);
  
  // 添加示例数据
  const points = generateRandomPoints([116.397428, 39.90923], 100, 0.2);
  heatmapLayer.addFeatures(points.map((coord, index) => ({
    id: `heat_${index}`,
    geometry: coord,
    properties: {
      weight: Math.random() * 10
    }
  })));
  
  updateInfo('热力图图层已添加');
};

window.updateHeatmapData = function() {
  if (!heatmapLayer) return;
  
  const points = generateRandomPoints([116.397428, 39.90923], 150, 0.25);
  heatmapLayer.updateData(points.map((coord, index) => ({
    id: `heat_${index}`,
    geometry: coord,
    properties: {
      weight: Math.random() * 10
    }
  })));
  
  updateInfo('热力图数据已更新');
};

window.removeHeatmapLayer = function() {
  if (!map || !heatmapLayer) return;
  
  map.removeLayer(heatmapLayer);
  heatmapLayer = null;
  updateInfo('热力图图层已移除');
};

// 矢量图层相关
window.addVectorLayer = function() {
  if (!map) return;
  
  if (vectorLayer) {
    map.removeLayer(vectorLayer);
  }
  
  vectorLayer = new VectorLayer({
    id: 'vector',
    styleFunction: (feature) => {
      const geometry = feature.getGeometry();
      if (geometry.getType() === 'Point') {
        return StyleUtil.createCircleStyle({
          radius: 8,
          fillColor: '#FF6B6B',
          strokeColor: '#fff',
          strokeWidth: 2
        });
      } else if (geometry.getType() === 'LineString') {
        return StyleUtil.createLineStyle({
          color: '#4ECDC4',
          width: 3
        });
      } else if (geometry.getType() === 'Polygon') {
        return StyleUtil.createPolygonStyle({
          fillColor: 'rgba(255, 107, 107, 0.3)',
          strokeColor: '#FF6B6B',
          strokeWidth: 2
        });
      }
      return null;
    }
  });
  
  map.addLayer(vectorLayer);
  
  // 添加示例数据
  const center = [116.397428, 39.90923];
  
  // 添加点
  vectorLayer.addFeature({
    id: 'point1',
    geometry: center,
    properties: { name: '示例点' }
  });
  
  // 添加线
  vectorLayer.addFeature({
    id: 'line1',
    geometry: [
      [center[0] - 0.01, center[1] - 0.01],
      [center[0], center[1]],
      [center[0] + 0.01, center[1] + 0.01]
    ],
    properties: { name: '示例线' }
  });
  
  // 添加面
  vectorLayer.addFeature({
    id: 'polygon1',
    geometry: [
      [center[0] - 0.02, center[1] - 0.02],
      [center[0] + 0.02, center[1] - 0.02],
      [center[0] + 0.02, center[1] + 0.02],
      [center[0] - 0.02, center[1] + 0.02],
      [center[0] - 0.02, center[1] - 0.02]
    ],
    properties: { name: '示例面' }
  });
  
  // 监听点击事件
  vectorLayer.on('featureclick', (data) => {
    console.log('要素被点击:', data);
    updateInfo(`要素被点击: ${data.properties.name || '未命名'}`);
  });
  
  updateInfo('矢量图层已添加');
}

// 企业级数据集成与管理示例
window.showDataIntegrationExample = function() {
  if (!map) return;
  
  // 初始化数据适配器
  dataAdapter = new DataAdapter({
    type: 'CSV',
    latField: 'lat',
    lonField: 'lng',
    idField: 'id'
  });
  
  // 创建数据图层
  if (dataLayer) {
    map.removeLayer(dataLayer);
  }
  
  dataLayer = new VectorLayer({
    id: 'data-integration',
    name: '企业数据图层',
    group: '业务图层',
    permissions: {
      visible: true,
      editable: true
    },
    styleFunction: (feature) => {
      const value = feature.get('sales');
      let color = '#4ECDC4';
      if (value > 5000) color = '#FF6B6B';
      else if (value > 2000) color = '#45B7D1';
      
      return StyleUtil.createCircleStyle({
        radius: 8,
        fillColor: color,
        strokeColor: '#fff',
        strokeWidth: 2
      });
    },
    onDataLoaded: (features) => {
      updateInfo(`数据加载完成，共加载 ${features.length} 条数据`);
    }
  });
  
  map.addLayer(dataLayer);
  
  // 模拟企业数据
  const mockData = [
    { id: 1, name: '门店A', lat: 39.90923, lng: 116.397428, sales: 5800, stock: 120, address: '北京市东城区' },
    { id: 2, name: '门店B', lat: 39.91923, lng: 116.407428, sales: 3200, stock: 85, address: '北京市西城区' },
    { id: 3, name: '门店C', lat: 39.89923, lng: 116.417428, sales: 1500, stock: 45, address: '北京市朝阳区' },
    { id: 4, name: '门店D', lat: 39.92923, lng: 116.387428, sales: 4700, stock: 98, address: '北京市海淀区' },
    { id: 5, name: '门店E', lat: 39.88923, lng: 116.377428, sales: 2800, stock: 67, address: '北京市丰台区' }
  ];
  
  // 使用数据适配器加载数据
  (async () => {
    try {
      await dataLayer.loadDataWithAdapter(mockData, {
        type: 'CSV',
        latField: 'lat',
        lonField: 'lng',
        idField: 'id'
      }, {
        chunkSize: 100,
        retryTimes: 3
      }, (progress) => {
        console.log(`加载进度: ${progress.loaded}/${progress.total}`);
      });
      
      // 绑定业务数据
      dataLayer.bindData('stockInfo', {
        1: { alert: '库存偏低', threshold: 150 },
        2: { alert: '正常', threshold: 100 },
        3: { alert: '库存偏低', threshold: 50 }
      });
      
      // 监听数据变化
      dataLayer.watchData(({ key, value }) => {
        console.log(`数据变化: ${key}`, value);
      });
      
      updateInfo('企业数据集成示例已加载');
    } catch (error) {
      updateInfo('数据加载失败: ' + error.message);
    }
  })();
};

// 模拟数据更新
window.simulateDataUpdate = function() {
  if (!dataLayer) {
    updateInfo('请先加载数据集成示例');
    return;
  }
  
  // 更新业务数据
  dataLayer.bindData('stockInfo', {
    1: { alert: '库存严重不足', threshold: 150 },
    2: { alert: '库存正常', threshold: 100 },
    3: { alert: '库存充足', threshold: 50 },
    4: { alert: '库存偏低', threshold: 100 },
    5: { alert: '库存充足', threshold: 80 }
  });
  
  updateInfo('数据已更新');
};

// 精细化图层管理示例
window.showLayerManagementExample = function() {
  if (!map) return;
  
  const layerManager = map.getLayerManager();
  
  // 创建多个分组图层
  const logisticsLayer1 = new VectorLayer({
    id: 'logistics-points',
    name: '配送点',
    group: '物流图层',
    visibilityRange: { minZoom: 10, maxZoom: 18 }
  });
  
  const logisticsLayer2 = new VectorLayer({
    id: 'logistics-routes',
    name: '配送路线',
    group: '物流图层',
    visibilityRange: { minZoom: 9, maxZoom: 18 }
  });
  
  const customerLayer = new VectorLayer({
    id: 'customer-layer',
    name: '客户分布',
    group: '客户图层',
    visibilityRange: { minZoom: 11, maxZoom: 18 }
  });
  
  // 添加图层到地图
  map.addLayer(logisticsLayer1);
  map.addLayer(logisticsLayer2);
  map.addLayer(customerLayer);
  
  // 添加一些示例数据
  const center = [116.397428, 39.90923];
  
  // 添加配送点
  const points = generateRandomPoints(center, 10, 0.05);
  logisticsLayer1.addFeatures(points.map((coord, index) => ({
    id: `logistics_${index}`,
    geometry: coord,
    properties: { name: `配送点${index + 1}` }
  })));
  
  // 添加客户点
  const customerPoints = generateRandomPoints(center, 15, 0.08);
  customerLayer.addFeatures(customerPoints.map((coord, index) => ({
    id: `customer_${index}`,
    geometry: coord,
    properties: { name: `客户${index + 1}` }
  })));
  
  // 演示图层权限控制
  window.setRolePermissions = function(role) {
    if (!map) return;
    
    let permissions = {};
    
    if (role === 'admin') {
      permissions = {
        'logistics-points': { visible: true, editable: true },
        'logistics-routes': { visible: true, editable: true },
        'customer-layer': { visible: true, editable: true }
      };
    } else if (role === 'operation') {
      permissions = {
        'logistics-points': { visible: true, editable: true },
        'logistics-routes': { visible: true, editable: true },
        'customer-layer': { visible: true, editable: false }
      };
    } else if (role === 'view-only') {
      permissions = {
        'logistics-points': { visible: true, editable: false },
        'logistics-routes': { visible: true, editable: false },
        'customer-layer': { visible: false, editable: false }
      };
    }
    
    map.setLayerPermissionsByRole(role, permissions);
    updateInfo(`已设置${role}角色权限`);
  };
  
  // 演示图层分组控制
  window.toggleLogisticsGroup = function() {
    const visible = !layerManager.getGroup('物流图层')[0]?.getVisible();
    map.setGroupVisibility('物流图层', visible);
    updateInfo(`物流图层组已${visible ? '显示' : '隐藏'}`);
  };
  
  window.toggleCustomerGroup = function() {
    const visible = !layerManager.getGroup('客户图层')[0]?.getVisible();
    map.setGroupVisibility('客户图层', visible);
    updateInfo(`客户图层组已${visible ? '显示' : '隐藏'}`);
  };
  
  updateInfo('图层管理示例已加载');
};

// 高性能与大规模数据支撑示例
window.showHighPerformanceExample = function() {
  if (!map) return;
  
  // 初始化样式缓存
  styleCache = StyleCache.getInstance();
  styleCache.setMaxCacheSize(2000);
  
  // 创建矢量瓦图层（示例使用，实际需要真实的矢量瓦片服务）
  if (vectorTileLayer) {
    map.removeLayer(vectorTileLayer);
  }
  
  vectorTileLayer = new VectorTileLayer({
    id: 'vector-tile',
    name: '矢量瓦片图层',
    useWebGL: true,
    webGLConfig: {
      colorMap: true,
      colorField: 'value',
      colorRange: ['#0000FF', '#FF0000']
    },
    // 这里使用模拟的URL，实际项目中需要替换为真实的矢量瓦片服务
    url: 'https://example.com/tiles/{z}/{x}/{y}.mvt',
    layerStyles: {
      'points': (feature, resolution) => {
        const value = feature.get('value') || 0;
        return styleCache.getStyle({
          image: {
            type: 'circle',
            radius: 6,
            fill: {
              color: value > 50 ? '#FF6B6B' : '#4ECDC4'
            },
            stroke: {
              color: '#ffffff',
              width: 1
            }
          }
        });
      },
      'polygons': {
        fill: {
          color: 'rgba(78, 205, 196, 0.3)'
        },
        stroke: {
          color: '#4ECDC4',
          width: 1
        }
      }
    }
  });
  
  // 由于没有真实的矢量瓦片服务，这里添加一个高性能的点图层作为示例
  const performanceLayer = new VectorLayer({
    id: 'performance-layer',
    name: '高性能图层',
    useWebGL: true,
    visibilityRange: { minZoom: 8, maxZoom: 18 }
  });
  
  map.addLayer(performanceLayer);
  
  // 生成大量点数据（模拟大规模数据）
  const center = [116.397428, 39.90923];
  const largePoints = generateRandomPoints(center, 5000, 0.15);
  
  // 批量添加数据
  (async () => {
    try {
      updateInfo('开始加载大量数据...');
      
      // 使用数据适配器批量加载
      await performanceLayer.loadDataWithAdapter(
        largePoints.map((coord, index) => ({
          id: `point_${index}`,
          lng: coord[0],
          lat: coord[1],
          value: Math.floor(Math.random() * 100),
          category: Math.random() > 0.5 ? 'A' : 'B'
        })),
        {
          type: 'CSV',
          latField: 'lat',
          lonField: 'lng',
          idField: 'id'
        },
        {
          chunkSize: 1000, // 分批处理
          skipErrors: true
        },
        (progress) => {
          // 显示加载进度
          const percent = Math.floor((progress.loaded / progress.total) * 100);
          updateInfo(`数据加载中: ${percent}%`);
        }
      );
      
      updateInfo(`高性能图层已加载，包含 ${largePoints.length} 个点`);
      console.log('样式缓存大小:', styleCache.getCacheSize());
    } catch (error) {
      updateInfo('高性能图层加载失败: ' + error.message);
    }
  })();
};

// 清理所有示例图层
window.clearAllExampleLayers = function() {
  if (!map) return;
  
  // 清理临时图层
  map.clearTempLayers();
  
  // 移除特定示例图层
  if (dataLayer) {
    map.removeLayer(dataLayer);
    dataLayer = null;
  }
  
  if (vectorTileLayer) {
    map.removeLayer(vectorTileLayer);
    vectorTileLayer = null;
  }
  
  updateInfo('所有示例图层已清理');
};;

window.removeVectorLayer = function() {
  if (!map || !vectorLayer) return;
  
  map.removeLayer(vectorLayer);
  vectorLayer = null;
  updateInfo('矢量图层已移除');
};

// 工具函数
function generateRandomPoints(center, count, radius) {
  const points = [];
  for (let i = 0; i < count; i++) {
    const angle = Math.random() * Math.PI * 2;
    const distance = Math.random() * radius;
    points.push([
      center[0] + Math.cos(angle) * distance,
      center[1] + Math.sin(angle) * distance
    ]);
  }
  return points;
}

function generateTrackPoints(center, count) {
  const points = [];
  let currentX = center[0];
  let currentY = center[1];
  
  for (let i = 0; i < count; i++) {
    currentX += (Math.random() - 0.5) * 0.02;
    currentY += (Math.random() - 0.5) * 0.02;
    points.push({
      coordinate: [currentX, currentY],
      time: Date.now() + i * 1000,
      properties: {
        speed: Math.random() * 60,
        direction: Math.random() * 360
      }
    });
  }
  
  return points;
}

function getExtentFromCoords(coords) {
  if (coords.length === 0) return [0, 0, 0, 0];
  
  let minX = coords[0][0];
  let minY = coords[0][1];
  let maxX = coords[0][0];
  let maxY = coords[0][1];
  
  coords.forEach(coord => {
    minX = Math.min(minX, coord[0]);
    minY = Math.min(minY, coord[1]);
    maxX = Math.max(maxX, coord[0]);
    maxY = Math.max(maxY, coord[1]);
  });
  
  // 添加一些边距
  const padding = 0.01;
  return [minX - padding, minY - padding, maxX + padding, maxY + padding];
}

function updateInfo(message) {
  const infoEl = document.getElementById('info');
  if (infoEl) {
    infoEl.textContent = message;
  }
}

// 标记点相关
window.addMarker = function() {
  if (!map) return;
  
  const center = map.getCenter();
  const marker = new Marker({
    id: `marker_${Date.now()}`,
    coordinate: center,
    draggable: true,
    title: '可拖拽标记点',
    onClick: (m) => {
      updateInfo('标记点被点击');
    },
    onDragEnd: (m, coord) => {
      updateInfo(`标记点已移动到: ${coord[0].toFixed(6)}, ${coord[1].toFixed(6)}`);
    }
  });
  
  map.addMarker(marker);
  markers.push(marker);
  updateInfo('标记点已添加');
};

window.showPopup = function() {
  if (!map) return;
  
  const center = map.getCenter();
  const popup = new Popup({
    id: 'test-popup',
    showCloseButton: true
  });
  popup.setContent(`
    <div style="padding: 10px;">
      <h4 style="margin: 0 0 10px 0;">示例弹窗</h4>
      <p>当前位置: ${center[0].toFixed(6)}, ${center[1].toFixed(6)}</p>
      <p>这是一个示例弹窗，可以显示任意HTML内容。</p>
    </div>
  `);
  popup.show(map.getOlMap(), center);
  map.addPopup(popup);
  updateInfo('弹窗已显示');
};

window.clearMarkers = function() {
  if (!map) return;
  
  map.clearAllMarkers();
  markers = [];
  updateInfo('所有标记点已清除');
};

// 测量工具相关
window.startMeasureDistance = function() {
  if (!map) return;
  
  if (!measureTool) {
    measureTool = new Measure({
      type: MeasureType.DISTANCE,
      showLabel: true
    });
    measureTool.init(map.getOlMap());
  }
  
  measureTool.start(MeasureType.DISTANCE);
  updateInfo('开始距离测量，在地图上绘制线条');
};

window.startMeasureArea = function() {
  if (!map) return;
  
  if (!measureTool) {
    measureTool = new Measure({
      type: MeasureType.AREA,
      showLabel: true
    });
    measureTool.init(map.getOlMap());
  }
  
  measureTool.start(MeasureType.AREA);
  updateInfo('开始面积测量，在地图上绘制多边形');
};

window.stopMeasure = function() {
  if (!measureTool) return;
  
  measureTool.stop();
  updateInfo('测量已停止');
};

window.clearMeasure = function() {
  if (!measureTool) return;
  
  measureTool.clear();
  updateInfo('测量结果已清除');
};

// 搜索工具相关
window.initSearch = function() {
  if (!map) return;
  
  if (!searchTool) {
    searchTool = new Search({
      provider: 'nominatim' // 使用 OpenStreetMap 的 Nominatim 服务
    });
    searchTool.init(map.getOlMap());
  }
  
  updateInfo('搜索工具已初始化');
};

window.testGeocode = async function() {
  if (!searchTool) {
    updateInfo('请先初始化搜索工具');
    return;
  }
  
  try {
    const results = await searchTool.geocode('北京市天安门');
    if (results.length > 0) {
      const result = results[0];
      map.setCenter(result.coordinate);
      map.setZoom(15);
      
      // 显示弹窗
      const popup = new Popup({
        showCloseButton: true
      });
      popup.setContent(`
        <div style="padding: 10px;">
          <h4 style="margin: 0 0 10px 0;">${result.name}</h4>
          <p>坐标: ${result.coordinate[0].toFixed(6)}, ${result.coordinate[1].toFixed(6)}</p>
        </div>
      `);
      popup.show(map.getOlMap(), result.coordinate);
      map.addPopup(popup);
      
      updateInfo(`找到 ${results.length} 个结果`);
    } else {
      updateInfo('未找到结果');
    }
  } catch (error) {
    updateInfo('搜索失败: ' + error.message);
  }
};

window.testReverseGeocode = async function() {
  if (!searchTool) {
    updateInfo('请先初始化搜索工具');
    return;
  }
  
  try {
    const center = map.getCenter();
    const result = await searchTool.reverseGeocode(center);
    if (result) {
      const popup = new Popup({
        showCloseButton: true
      });
      popup.setContent(`
        <div style="padding: 10px;">
          <h4 style="margin: 0 0 10px 0;">当前位置</h4>
          <p>${result.address || result.name}</p>
        </div>
      `);
      popup.show(map.getOlMap(), center);
      map.addPopup(popup);
      
      updateInfo('逆地理编码成功');
    } else {
      updateInfo('未找到结果');
    }
  } catch (error) {
    updateInfo('逆地理编码失败: ' + error.message);
  }
};

// 路线规划相关
window.initRoute = function() {
  if (!map) return;
  
  if (!routeTool) {
    routeTool = new Route({
      provider: 'osrm' // 使用 OSRM 服务
    });
    routeTool.init(map.getOlMap());
  }
  
  updateInfo('路线规划工具已初始化');
};

window.testRoute = async function() {
  if (!routeTool) {
    updateInfo('请先初始化路线规划工具');
    return;
  }
  
  try {
    const center = map.getCenter();
    const routeResult = await routeTool.plan([
      {
        coordinate: [center[0] - 0.01, center[1] - 0.01],
        name: '起点',
        type: 'start'
      },
      {
        coordinate: [center[0] + 0.01, center[1] + 0.01],
        name: '终点',
        type: 'end'
      }
    ]);
    
    updateInfo(`路线规划完成，距离: ${(routeResult.distance / 1000).toFixed(2)} km`);
  } catch (error) {
    updateInfo('路线规划失败: ' + error.message);
  }
};

window.clearRoute = function() {
  if (!routeTool) return;
  
  routeTool.clear();
  updateInfo('路线已清除');
};

// 全屏控件
window.addFullScreen = function() {
  if (!map) return;
  
  const fullScreen = new FullScreen({
    tipLabel: '全屏',
    position: 'top-right'
  });
  
  map.addControl(fullScreen);
  updateInfo('全屏控件已添加');
};

// 初始化
initMap();

// 测试空间分析功能
function testSpatialAnalysis() {
  console.log('=== 空间分析功能测试 ===');
  
  // 1. 距离测量示例
  const point1 = [116.3974, 39.9093]; // 北京天安门
  const point2 = [116.4074, 39.9193]; // 附近点
  const distance = SpatialAnalysis.distance(point1, point2, 'km');
  console.log('两点距离(公里):', distance);
  
  // 2. 路径长度测量
  const path = [
    [116.3974, 39.9093],
    [116.4074, 39.9193],
    [116.4174, 39.9293]
  ];
  const pathLength = SpatialAnalysis.measureDistance(path, 'km');
  console.log('路径总长度(公里):', pathLength);
  
  // 3. 多边形面积测量
  const polygon = [
    [116.3974, 39.9093],
    [116.4074, 39.9093],
    [116.4074, 39.9193],
    [116.3974, 39.9193]
  ];
  const area = SpatialAnalysis.measureArea(polygon, 'km²');
  console.log('多边形面积(平方公里):', area);
  
  // 4. 缓冲区分析
  const buffer = SpatialAnalysis.buffer(point1, 5000); // 5公里缓冲区
  console.log('缓冲区坐标数量:', buffer.length);
  
  // 5. 点是否在多边形内
  const testPoint = [116.4024, 39.9143];
  const isInside = SpatialAnalysis.isPointInPolygon(testPoint, polygon);
  console.log('点是否在多边形内:', isInside);
  
  // 6. 物流路径优化
  const start = point1;
  const destinations = [
    [116.4074, 39.9193],
    [116.4174, 39.9293],
    [116.3874, 39.8993],
    [116.3774, 39.8893]
  ];
  const optimizedPath = LogisticsAnalyzer.optimizeRoutes(start, destinations);
  console.log('优化后的配送顺序索引:', optimizedPath);
  
  // 7. 禁运区域检查
  const forbiddenZone = polygon;
  const pointsToCheck = [point1, point2, testPoint];
  const forbiddenCheckResult = LogisticsAnalyzer.checkForbiddenZones(pointsToCheck, [forbiddenZone]);
  console.log('禁运区域检查结果:', forbiddenCheckResult);
  
  // 可视化缓冲区示例
  if (map) {
    // 创建缓冲区图层
    const bufferLayer = new VectorLayer({
      id: 'buffer-layer',
      name: '缓冲区示例',
      data: [{
        type: 'Feature',
        geometry: {
          type: 'Polygon',
          coordinates: [buffer]
        },
        properties: {
          name: '5公里缓冲区'
        }
      }],
      style: {
        fill: { color: 'rgba(0, 0, 255, 0.2)' },
        stroke: { color: 'blue', width: 2 }
      }
    });
    map.addLayer(bufferLayer);
    
    // 创建测试点图层
    // const testLayer = new ImageLayer({
    //   id: 'test-points-layer',
    //   name: '测试点',
    //   data: pointsToCheck.map((point, index) => ({
    //     lon: point[0],
    //     lat: point[1],
    //     name: `测试点${index + 1}`,
    //     icon: {
    //       src: index === 0 ? 'https://openlayers.org/en/v4.6.5/examples/data/icon.png' : 'https://openlayers.org/en/v4.6.5/examples/data/blueIcon.png'
    //     }
    //   }))
    // });
    // map.addLayer(testLayer);
    
    console.log('空间分析可视化已添加到地图');
  }
}

// 延迟执行空间分析测试，确保地图已初始化
setTimeout(() => {
  testSpatialAnalysis();
  testExtensions();
}, 2000);

// 测试扩展功能
function testExtensions() {
  console.log('=== 测试扩展功能 ===');
  
  // 使用地图自带的扩展管理
  map.registerExtension('testExtension', {
    name: 'test',
    version: '1.0.0',
    init: () => console.log('Test extension initialized'),
    destroy: () => console.log('Test extension destroyed')
  });
  
  // 获取扩展
  const testExt = map.getExtension('testExtension');
  console.log('Test extension:', testExt);
  
  // 移除扩展
  map.removeExtension('testExtension');
  console.log('Test extension removed');
  
  console.log('=== 测试扩展管理器 ===');
  // 使用 ExtensionManager
  // const { ExtensionManager, MeasurementExtension, RouteExtension } = ZSSOLMap;
  const extManager = new ExtensionManager(map);
  
  // 创建测量扩展
  const measureExt = new MeasurementExtension(map);
  extManager.register(measureExt);
  
  // 创建路线规划扩展
  const routeExt = new RouteExtension(map);
  extManager.register(routeExt);
  
  // 使用扩展功能
  measureExt.startMeasurement('distance');
  console.log('Measurement extension active:', measureExt.isActive);
  
  // 路线规划示例
  routeExt.planRoute([120.12, 30.28], [121.48, 31.22])
    .then(result => console.log('Route plan result:', result));
  
  // 获取所有扩展
  const allExts = extManager.getAll();
  console.log('All extensions:', Array.from(allExts.keys()));
  
  console.log('=== 扩展功能测试完成 ===');
}

// 添加一些UI提示
console.log('=== zss-ol-map 增强功能示例 ===');
console.log('可用的新功能测试函数:');
console.log('1. showDataIntegrationExample() - 测试企业级数据集成能力');
console.log('2. simulateDataUpdate() - 模拟业务数据更新');
console.log('3. showLayerManagementExample() - 测试图层管理与权限控制');
console.log('4. setRolePermissions(role) - 设置角色权限 (admin/operation/view-only)');
console.log('5. toggleLogisticsGroup() - 切换物流图层组显示');
console.log('6. toggleCustomerGroup() - 切换客户图层组显示');
console.log('7. showHighPerformanceExample() - 测试高性能大规模数据渲染');
console.log('8. clearAllExampleLayers() - 清理所有示例图层');

